import fs from "fs";
import {join} from "path";
import {routesTemplate} from "./template.js";
const  transformType = (value)=>{
    if(value === 'true'){
        return true
    }else if(value === 'false'){
        return false
    }
    return value;
}
const getMeta = (content)=>{
    const meta = {};
    let metaString = content.split('***********#**************')[1]?.split('---------meta数据---------')[1];
    metaString = metaString?metaString.replaceAll(' ',''):'';
    let metaApp =metaString.split('\n');
    metaApp.shift();
    metaApp.pop();
    metaApp = metaApp?.map((value)=>value.split('='))
    if(metaApp){
        for(const item of metaApp){
            meta[item[0].replaceAll('*','')] = transformType(item[1]);
        }
    }
    return meta;
}
const updateRouter = (path, father,isupdate = true) => {
    const dir = fs.readdirSync(path);
    for (let item of dir) {
        let fPath = join(path, item);
        let stat = fs.statSync(fPath);
        if (stat.isDirectory()) {
            const fileContent = fs.readFileSync(fPath + '\\index.jsx',"utf-8")
            const pathArr = fPath.split('\\');
            pathArr.shift()
            pathArr.shift()
            const route = {
                path: '/' + pathArr.join('/').toLowerCase(),
                componentPath: '../../' + fPath.replaceAll('\\', '/'),
                children: [],
                meta:getMeta(fileContent)
            }
            father.push(route)
            updateRouter(fPath, route.children);
        }
    }
}
const routers = []
updateRouter('./src/views', routers);
routers.push({
    path:'*',
    componentPath:'../assets/notFound/',
    children: [],
})
fs.writeFileSync('./src/routes/routes.js', routesTemplate(`const routes = ${JSON.stringify(routers)}`));
export default updateRouter;